<template>
  <nav id="nav1">
    <el-row align="center">
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17">
        <el-menu
          :default-active="activepath"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
          router
          background-color="#f0f0f0"
          text-color="#333"
          active-text-color="#0084ff"
        >
          <el-menu-item
            v-for="(item, i) in navList"
            :key="i"
            :index="item.name"
          >
            <template slot="title">
              <span> {{ item.navItem }}</span>
            </template>
          </el-menu-item>
        </el-menu>
      </el-col>
      <el-col class="right-menu" :xs="24" :sm="24" :md="4" :lg="4" :xl="5">
        <div v-if="!username">
          <el-button type="success" @click="addgsForm" icon="el-icon-edit"
            >登录</el-button
          >
          <el-button type="info" @click="goRegist" icon="el-icon-edit"
            >注册</el-button
          >
        </div>
        <div index="999" class="right-menu" v-if="username">
          <template>
            <el-tooltip content="Global Size" effect="dark" placement="bottom">
              <el-dropdown trigger="click" @command="handleSetSize">
                <div>
                  <!-- <svg-icon class-name="size-icon" icon-class="size" /> -->
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="item of sizeOptions"
                    :key="item.value"
                    :disabled="size === item.value"
                    :command="item.value"
                  >
                    {{ item.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-tooltip>
          </template>
          <el-dropdown
            class="avatar-container right-menu-item hover-effect"
            trigger="click"
          >
            <div class="avatar-wrapper">
              <img :src="avatar" class="user-avatar" />
              <i class="el-icon-caret-bottom" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <router-link to="/person/index">
                <el-dropdown-item>个人中心</el-dropdown-item>
              </router-link>
              <router-link to="/">
                <el-dropdown-item>Dashboard</el-dropdown-item>
              </router-link>
              <a
                target="_blank"
                href="https://github.com/PanJiaChen/vue-element-admin/"
              >
                <el-dropdown-item>Github</el-dropdown-item>
              </a>
              <a
                target="_blank"
                href="https://panjiachen.github.io/vue-element-admin-site/#/"
              >
                <el-dropdown-item>Docs</el-dropdown-item>
              </a>
              <el-dropdown-item divided @click.native="logout">
                <span style="display: block">Log Out</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
    </el-row>
    <div></div>
    <div>
      <el-dialog
        title="登录"
        :visible.sync="dialogAddgsVisible"
        @close="closeDialogAddgsVisible"
        append-to-body
      >
        <el-form :model="loginForm" :rules="rules" ref="loginForm">
          <el-row>
            <el-form-item label="用户名：" prop="username">
              <el-input class="search-input" v-model="loginForm.username" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input
                type="password"
                class="search-input"
                v-model="loginForm.password"
              />
            </el-form-item>
          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddgsVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveloginForm('loginForm')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </nav>
</template>

<script>
import { Message } from "element-ui";
import { mapGetters } from 'vuex'
export default {
  name: "Header",
  data() {
    return {
      isFixed: false,
      username: "",
      redirect: "",
      otherQuery: {},
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 5,
            message: "长度在 2 到 5 个字符",
          },
          // {
          //   pattern: /^[\u4E00-\u9FA5]+$/,
          //   message: "用户名只能为中文",
          // },
          //{ pattern:/^[a-zA-Z]w{1,4}$/, message: '以字母开头，长度在2-5之间， 只能包含字符、数字和下划线'}
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },

      loginForm: {
        username: "admin",
        password: "admin",
      },
      dialogAddgsVisible: false,
      dialogRegistVisible: false,
      sizeOptions: [
        { label: "Default", value: "default" },
        { label: "Medium", value: "medium" },
        { label: "Small", value: "small" },
        { label: "Mini", value: "mini" },
      ],
      size: "100%",
      sidebar: "sidebar",
      device: "mobel",
      activepath: window.localStorage.getItem("activePath"),
      screenWidth: document.body.clientWidth,
      navList: [
        { name: "/", navItem: "技术" },
        { name: "/about", navItem: "前端" },
        { name: "/about", navItem: "后端" },
        { name: "/hello", navItem: "学习" },
        { name: "/Markdown", navItem: "发包" },
        { name: "/reource", navItem: "资源" },
        { name: "/neitui", navItem: "内推" },
      ],
    };
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  created() {
    if (this.$route.query.login) this.dialogAddgsVisible = true;
  },
  watch: {
    screenWidth(newValue) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = newValue;
        this.timer = true;
        setTimeout(() => {
          //console.log(this.screenWidth);
          this.timer = false;
        }, 400);
      }
    },
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  methods: {
    /**
     *点击新增按钮，弹出新增模态框
     * @param
     */
    addgsForm() {
      this.dialogAddgsVisible = true;
      this.title = "新增分类";
    },
    /**
     *确定新增数据
     * @param
     */
    saveloginForm(aaa) {
      this.$refs[aaa].validate((valid) => {
        if (valid) {
          let params = {
            username: this.loginForm.username,
            password: this.loginForm.password,
          };

          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((data) => {
              this.dialogAddgsVisible = false;
              this.username = data.username;
              this.loading = false;
              Message({
                message: "login sucess",
                type: "sucess",
                duration: 3 * 1000,
              });
            })
            .catch(() => {
              this.loading = false;

              // this.$message({
              //   message: "Switch Size Success",
              //   type: "success",
              // });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /**
     *关闭或取消模态框，清空值
     * @param
     */
    closeDialogAddgsVisible() {
      this.$refs.loginForm.resetFields(); //element封装的方法,清空模态框的值
      this.title = ""; //初始化title的值
      this.loginForm = {
        //初始化loginForm中的值
        name: "",
        sort: "",
      };
    },
    handleSetSize(size) {
      this.$ELEMENT.size = size;
      this.$store.dispatch("app/setSize", size);
      this.refreshView();
      this.$message({
        message: "Switch Size Success",
        type: "success",
      });
    },
    refreshView() {
      // In order to make the cached page re-rendered
      this.$store.dispatch("tagsView/delAllCachedViews", this.$route);

      const { fullPath } = this.$route;

      this.$nextTick(() => {
        this.$router.replace({
          path: "/redirect" + fullPath,
        });
      });
    },
    handleSelect(key, keyPath) {
      if (key == "999") {
        return false;
      }
      document
        .querySelectorAll(".el-menu-item.is-active")
        .forEach((item) => item.classList.remove("is-active"));
      event.currentTarget.classList.add("is-active");
      console.log(key, keyPath);
      window.localStorage.setItem("activeMenu", key);
    },
    goRegist() {
      this.$router.push("/regist");
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>
<style lang="scss" scoped>
.el-menu-item.is-active {
  background-color: rgb(231, 235, 240) !important;
  color: #409eff !important;
}
#nav1 {
  background: rgb(240, 240, 240);
  position: -webkit-sticky;
  position: sticky;
  top: 0px;
  span {
    font-size: 1.2em;
    font-weight: bold;
  }
}

#nav1 a.router-link-exact-active {
  color: #42b983;
}
.right {
  float: right;
}
.right-menu {
  float: right;
  vertical-align: bottom;
  height: 100%;
  line-height: 100%;

  &:focus {
    outline: none;
  }

  .right-menu-item {
    display: inline-block;
    padding: 0 8px;
    height: 100%;
    font-size: 18px;
    color: #5a5e66;
    vertical-align: text-bottom;

    &.hover-effect {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: rgba(0, 0, 0, 0.025);
      }
    }
  }

  .avatar-container {
    margin-right: 30px;

    .avatar-wrapper {
      margin-top: 5px;
      position: relative;

      .user-avatar {
        cursor: pointer;
        width: 40px;
        height: 40px;
        border-radius: 10px;
      }

      .el-icon-caret-bottom {
        cursor: pointer;
        position: absolute;
        right: -20px;
        top: 25px;
        font-size: 12px;
      }
    }
  }
}
</style>
